/*
 * Copyright 2016-2022 dromara.org.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dromara.mendmix.gateway.filter.subhandler;

import org.dromara.mendmix.cache.CacheUtils;
import org.dromara.mendmix.common.CustomRequestHeaders;
import org.dromara.mendmix.common.model.ApiInfo;
import org.dromara.mendmix.gateway.GatewayConstants;
import org.dromara.mendmix.gateway.filter.SubFilterHandler;
import org.dromara.mendmix.gateway.helper.RequestContextHelper;
import org.dromara.mendmix.gateway.model.BizSystemModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.reactive.ServerHttpRequest.Builder;
import org.springframework.web.server.ServerWebExchange;

/**
 * 
 * 
 * @description <br>
 * @author <a href="mailto:vakinge@gmail.com">jiangwei</a>
 * @date 2020年4月16日
 */
public class CachingResponseHandler implements SubFilterHandler {

	private static Logger logger = LoggerFactory.getLogger("org.dromara.mendmix.gateway");
	
	@Override
	public Object preHandle(ServerWebExchange exchange,BizSystemModule module,Builder requestBuilder) {
		ApiInfo currentApi = RequestContextHelper.getCurrentApi(exchange);
		if(currentApi == null || currentApi.getRespCacheTTL() <= 0)return null;
		//
		String hitKey = RequestContextHelper.getCurrentRequestHitKey(exchange, false);
		String cachingBody = CacheUtils.getStr(hitKey);
		if(cachingBody != null) {
			exchange.getResponse().getHeaders().add(CustomRequestHeaders.HEADER_HIT_CACHE_KEY, hitKey);
			if(RequestContextHelper.isDebugMode(exchange)) {
				String requestUri = RequestContextHelper.getOriginRequestUri(exchange);
				logger.info("请求【{}】命中缓存Key:{}",requestUri,hitKey);
			}
			return cachingBody;
		}
		return null;
	}

	@Override
	public String postHandle(ServerWebExchange exchange,boolean successed,String responseBody) {
		String hitKey;
    	if(successed && (hitKey = exchange.getAttribute(GatewayConstants.CONTEXT_CURRENT_HIT_KEY)) != null) {
    		ApiInfo currentApi = RequestContextHelper.getCurrentApi(exchange);
    		if(currentApi == null || currentApi.getRespCacheTTL() <= 0)return null;
    		CacheUtils.setStr(hitKey, responseBody, currentApi.getRespCacheTTL());
    		if(RequestContextHelper.isDebugMode(exchange)) {
				String requestUri = RequestContextHelper.getOriginRequestUri(exchange);
				logger.info("请求【{}】写入缓存Key:{}",requestUri,hitKey);
			}
    	}
    	return null;
	}
	
	@Override
	public int ordered() {
		return 0;
	}

}
